const log = require('../util/log'),
  zoroDB = require('../util/zoroDB'),
  SQL_FIELDS = ['name', 'value'];

exports.select = obj => {
  var sql = 'select * from system where 1=1',
    paras = [];
  for (var key in obj) {
    if (SQL_FIELDS.indexOf(key) != -1) {
      sql += ' and ' + key + '=?';
      paras.push(obj[key])
    }
  }
  return new Promise((resolve, reject) => {
    zoroDB.query(sql, paras, (err, rows, fields) => {
      if (err) {
        reject(err)
        return
      }
      rows.forEach(row => {
        exports.fillProp(row)
      })
      resolve(rows)
    })
  })
}

exports.fillProp = system => {
}

exports.insert = obj => {
  var sql = 'insert into system(',
    paras = [];
  SQL_FIELDS.forEach(item => {
    sql += item + ','
    paras.push(obj[item])
  })
  sql = sql.substring(0, sql.length - 1) + ') values('
  SQL_FIELDS.forEach(item => {
    sql += '?,'
  })
  sql = sql.substring(0, sql.length - 1) + ')'
  return new Promise((resolve, reject) => {
    zoroDB.query(sql, paras, (err, result) => {
      if (err) {
        reject(err)
        return
      }
      resolve()
    })
  })
}

exports.update = obj => {
  var sql = 'update system set',
    paras = [];
  for (var key in obj) {
    if (SQL_FIELDS.indexOf(key) != -1) {
      sql += ' ' + key + '=?,';
      paras.push(obj[key])
    }
  }
  sql = sql.substring(0, sql.length - 1) + ' where name=?'
  paras.push(obj.name)
  return new Promise((resolve, reject) => {
    zoroDB.query(sql, paras, (err, result) => {
      if (err) {
        reject(err)
        return
      }
      resolve()
    })
  })
}
